<template>
  <div class="home" v-if="refresh" :key="refresh">
    <front-header></front-header>
    <div class="main-content">
      <front-carousel></front-carousel>
      <front-category></front-category>

      <!-- 推荐商品区域 -->
      <div class="section">
        <div class="section-header">
          <div class="title-wrapper">
            <h2 class="section-title">商品</h2>
            <div class="title-line"></div>
          </div>
          <div class="more-btn" @click="$router.push('/products')">
            <span>查看更多</span>
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
        <el-row :gutter="20">
          <el-col :span="6" v-for="product in recommendProducts" :key="product.id">
            <product-card :product="product" @add-to-cart="handleAddToCart" @toggle-favorite="handleToggleFavorite"></product-card>
          </el-col>
        </el-row>
      </div>

      <!-- 新品上市区域 -->
      <div class="section">
        <div class="section-header">
          <div class="title-wrapper">
            <h2 class="section-title">新品上市</h2>
            <div class="title-line"></div>
          </div>
          <div class="more-btn" @click="$router.push('/products?type=new')">
            <span>查看更多</span>
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
        <el-row :gutter="20">
          <el-col :span="6" v-for="product in newProducts" :key="product.id">
            <product-card :product="product" @add-to-cart="handleAddToCart" @toggle-favorite="handleToggleFavorite"></product-card>
          </el-col>
        </el-row>
      </div>
    </div>
    <front-footer></front-footer>
  </div>
</template>

<script>
import FrontHeader from '@/components/front/FrontHeader.vue'
import FrontFooter from '@/components/front/FrontFooter.vue'
import FrontCarousel from '@/components/front/FrontCarousel.vue'
import FrontCategory from '@/components/front/FrontCategory.vue'
import ProductCard from '@/components/front/ProductCard.vue'
import Request from '@/utils/request'

export default {
  name: 'Home',
  components: {
    FrontHeader,
    FrontFooter,
    FrontCarousel,
    FrontCategory,
    ProductCard
  },
  data() {
    return {
      recommendProducts: [],
      newProducts: [],
      isLoggedIn: false,
      refresh: true
    }
  },
  computed: {
   
  },
  methods: {
    // 修改 checkLoginStatus 方法
    checkLoginStatus() {
      const token = localStorage.getItem('token');
      const userStr = localStorage.getItem('frontUser');
      
      if (token && userStr) {
        try {
          const user = JSON.parse(userStr);
       
          // 检查用户角色，如果不是 USER 则注销
          if (user.role !== 'USER') {
            this.logout();
            this.$message.warning('请使用普通用户账号访问');
            return;
          }
          this.isLoggedIn = true;
        } catch (error) {
          this.logout();
        }
      } else {
        this.isLoggedIn = false;
      }
    },

    // 修改 logout 方法
    logout() {
      localStorage.removeItem('token');
      localStorage.removeItem('frontUser');
      this.isLoggedIn = false;
      // 强制刷新整个页面
      window.location.reload()
   
    },

    // 获取推荐商品
    async getRecommendProducts() {
      try {
        // 重新检查登录状态
        this.checkLoginStatus();
        
        let products = [];
        
        if (!this.isLoggedIn) {
          // 未登录状态 - 获取随机排序的前8条商品
          const res = await Request.get('/product/page?status=1&size=8');
          if (res.code === '0') {
            products = res.data.records || res.data;
            // 随机排序
            products = products.sort(() => Math.random() - 0.5);
          }
        } else {
          // 登录状态 - 获取个性化推荐
          const userStr = localStorage.getItem('frontUser');
          if (!userStr) {
            throw new Error('User info not found');
          }
          const userId = JSON.parse(userStr).id;
          const res = await Request.get('/product/page?status=1&size=8');
          //const res = await Request.get(`/recommend/user/${userId}`);
          if (res.code === '0') {
            products = res.data.records || res.data;
          }
          
          // 获取收藏状态
          try {
            const favRes = await Request.get(`/favorite/user/${userId}`);
            if (favRes.code === '0') {
              const favorites = favRes.data;
              products = products.map(product => ({
                ...product,
                isFavorite: favorites.some(f => f.productId === product.id && f.status === 1)
              }));
            }
          } catch (error) {
            console.error('获取收藏状态失败:', error);
            products = products.map(product => ({
              ...product,
              isFavorite: false
            }));
          }
        }

        // 设置推荐商品
        this.recommendProducts = products.map(product => ({
          ...product,
          isFavorite: product.isFavorite || false
        }));

      } catch (error) {
        console.error('获取推荐商品失败:', error);
        // 如果获取失败，回退到未登录状态的推荐
        this.isLoggedIn = false;
        this.getRecommendProducts();
      }
    },
    // 获取新品
    async getNewProducts() {
      try {
        const res = await Request.get('/product/page?status=1&sort=updatedAt,desc&size=4')
        if (res.code === '0') {
          this.newProducts = res.data.records.map(product => ({
            ...product,
            isFavorite: false
          }))
        }
      } catch (error) {
        console.error('获取新品失败:', error)
      }
    },
    // 添加到购物车
    handleAddToCart(product) {
      this.$message({
        type: 'success',
        message: '已添加到购物车'
      })
    },
    // 切换收藏状态
    async handleToggleFavorite({ product, status }) {
      // 更新本地数据
      const targetProduct = this.recommendProducts.find(p => p.id === product.id)
      if (targetProduct) {
        targetProduct.isFavorite = status === 1
      }
      
      // 重新获取推荐商品列表
      await this.getRecommendProducts()
    }
  },
  created() {
    // 添加登录状态检查
    this.checkLoginStatus();
    this.getRecommendProducts();
    this.getNewProducts();
  },
  mounted() {
    const userStr = localStorage.getItem('frontUser');
    if (userStr) {
      this.isLoggedIn = true;
    }
  }
}
</script>

<style scoped>
.home {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #e8f5e9 0%, #fffde7 100%);
}
.main-content {
  flex: 1;
  padding: 0 20px;
  max-width: 1400px;
  margin: 0 auto;
  width: 100%;
  box-sizing: border-box;
}
.section {
  margin: 48px 0;
  background: rgba(232,245,233,0.5);
  border-radius: 22px;
  box-shadow: 0 8px 32px rgba(103,194,58,0.10);
  padding: 32px 28px 24px 28px;
  position: relative;
}
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}
.title-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  gap: 12px;
}
.section-title {
  margin: 0;
  font-size: 28px;
  font-weight: 700;
  color: #388e3c;
  position: relative;
  z-index: 1;
  letter-spacing: 1.2px;
}
.title-line {
  position: absolute;
  bottom: 4px;
  left: 0;
  width: 100%;
  height: 8px;
  background: linear-gradient(90deg, #a5d6a7 60%, #e8f5e9 100%);
  border-radius: 4px;
  z-index: 0;
}
.more-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 22px;
  border-radius: 22px;
  background: linear-gradient(90deg, #e8f5e9 60%, #fffde7 100%);
  color: #43a047;
  font-size: 15px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1.5px solid #a5d6a7;
}
.more-btn:hover {
  background: #e8f5e9;
  transform: translateX(4px);
  color: #388e3c;
}
.more-btn i {
  font-size: 15px;
  transition: transform 0.3s ease;
}
.more-btn:hover i {
  transform: translateX(2px);
}
.section::before {
  content: '';
  position: absolute;
  left: 24px;
  top: 18px;
  width: 48px;
  height: 48px;
  background: url('data:image/svg+xml;utf8,<svg width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg"><ellipse cx="24" cy="24" rx="22" ry="10" fill="%23e8f5e9"/><path d="M10 34 Q24 8 38 34" stroke="%2367c23a" stroke-width="2" fill="none"/><ellipse cx="24" cy="24" rx="4" ry="8" fill="%23a5d6a7"/></svg>') no-repeat center/contain;
  opacity: 0.18;
  z-index: 0;
}
.el-col {
  margin-bottom: 30px;
}
.section:last-child .el-col {
  margin-bottom: 0;
}
@media (max-width: 900px) {
  .main-content {
    padding: 0 4px;
  }
  .section {
    border-radius: 12px;
    padding: 16px 4px 12px 4px;
  }
  .section-title {
    font-size: 18px;
  }
}
</style> 